package com.music.note_android.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class ThumbnailGenerator(private val context: Context) {
    
    companion object {
        private const val THUMBNAIL_WIDTH = 200
        private const val THUMBNAIL_HEIGHT = 200
        private const val THUMBNAIL_QUALITY = 80
        private const val THUMBNAIL_DIR = "thumbnails"
    }
    
    /**
     * 为笔记生成缩略图
     * @param noteId 笔记ID
     * @param dataPath 笔记数据文件路径
     * @return 缩略图文件路径，如果生成失败返回null
     */
    suspend fun generateThumbnail(noteId: String, dataPath: String): String? {
        return withContext(Dispatchers.IO) {
            try {
                val dataFile = File(dataPath)
                if (!dataFile.exists()) {
                    return@withContext null
                }
                
                // 创建缩略图目录
                val thumbnailDir = File(context.filesDir, THUMBNAIL_DIR)
                if (!thumbnailDir.exists()) {
                    thumbnailDir.mkdirs()
                }
                
                // 生成缩略图文件路径
                val thumbnailFile = File(thumbnailDir, "${noteId}_thumb.jpg")
                
                // 根据数据文件类型生成缩略图
                val bitmap = when {
                    isImageFile(dataPath) -> generateImageThumbnail(dataPath)
                    isTextFile(dataPath) -> generateTextThumbnail(dataPath)
                    else -> generateDefaultThumbnail()
                }
                
                bitmap?.let {
                    saveBitmapToFile(it, thumbnailFile)
                    it.recycle()
                    return@withContext thumbnailFile.absolutePath
                }
                
                null
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }
    }
    
    /**
     * 删除缩略图文件
     */
    suspend fun deleteThumbnail(thumbnailPath: String) {
        withContext(Dispatchers.IO) {
            try {
                val file = File(thumbnailPath)
                if (file.exists()) {
                    file.delete()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    /**
     * 生成图片缩略图
     */
    private fun generateImageThumbnail(imagePath: String): Bitmap? {
        return try {
            val options = BitmapFactory.Options().apply {
                inJustDecodeBounds = true
            }
            BitmapFactory.decodeFile(imagePath, options)
            
            // 计算缩放比例
            val scaleFactor = calculateInSampleSize(options, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)
            
            options.apply {
                inJustDecodeBounds = false
                inSampleSize = scaleFactor
            }
            
            val bitmap = BitmapFactory.decodeFile(imagePath, options)
            bitmap?.let { scaleBitmap(it, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT) }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
    
    /**
     * 生成文本缩略图
     */
    private fun generateTextThumbnail(textPath: String): Bitmap? {
        return try {
            val file = File(textPath)
            val text = file.readText().take(100) // 读取前100个字符
            
            val bitmap = Bitmap.createBitmap(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            
            // 设置背景色
            canvas.drawColor(Color.WHITE)
            
            // 设置文字画笔
            val paint = Paint().apply {
                color = Color.BLACK
                textSize = 12f
                isAntiAlias = true
            }
            
            // 绘制文字
            val lines = text.split("\n")
            var y = 20f
            val lineHeight = 16f
            
            for (line in lines) {
                if (y > THUMBNAIL_HEIGHT - lineHeight) break
                
                val words = line.split(" ")
                var currentLine = ""
                
                for (word in words) {
                    val testLine = if (currentLine.isEmpty()) word else "$currentLine $word"
                    val bounds = Rect()
                    paint.getTextBounds(testLine, 0, testLine.length, bounds)
                    
                    if (bounds.width() > THUMBNAIL_WIDTH - 20) {
                        if (currentLine.isNotEmpty()) {
                            canvas.drawText(currentLine, 10f, y, paint)
                            y += lineHeight
                            currentLine = word
                        } else {
                            // 单词太长，截断
                            canvas.drawText(word.take(20), 10f, y, paint)
                            y += lineHeight
                        }
                    } else {
                        currentLine = testLine
                    }
                    
                    if (y > THUMBNAIL_HEIGHT - lineHeight) break
                }
                
                if (currentLine.isNotEmpty() && y <= THUMBNAIL_HEIGHT - lineHeight) {
                    canvas.drawText(currentLine, 10f, y, paint)
                    y += lineHeight
                }
            }
            
            bitmap
        } catch (e: Exception) {
            e.printStackTrace()
            generateDefaultThumbnail()
        }
    }
    
    /**
     * 生成默认缩略图
     */
    private fun generateDefaultThumbnail(): Bitmap {
        val bitmap = Bitmap.createBitmap(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        
        // 设置背景色
        canvas.drawColor(Color.LTGRAY)
        
        // 绘制笔记图标
        val paint = Paint().apply {
            color = Color.GRAY
            textSize = 48f
            isAntiAlias = true
            textAlign = Paint.Align.CENTER
        }
        
        canvas.drawText("📝", THUMBNAIL_WIDTH / 2f, THUMBNAIL_HEIGHT / 2f + 16f, paint)
        
        return bitmap
    }
    
    /**
     * 缩放位图
     */
    private fun scaleBitmap(bitmap: Bitmap, targetWidth: Int, targetHeight: Int): Bitmap {
        return Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true)
    }
    
    /**
     * 计算缩放比例
     */
    private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
        val height = options.outHeight
        val width = options.outWidth
        var inSampleSize = 1
        
        if (height > reqHeight || width > reqWidth) {
            val halfHeight = height / 2
            val halfWidth = width / 2
            
            while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
                inSampleSize *= 2
            }
        }
        
        return inSampleSize
    }
    
    /**
     * 保存位图到文件
     */
    private fun saveBitmapToFile(bitmap: Bitmap, file: File) {
        try {
            FileOutputStream(file).use { out ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, THUMBNAIL_QUALITY, out)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    
    /**
     * 判断是否为图片文件
     */
    private fun isImageFile(path: String): Boolean {
        val extension = File(path).extension.lowercase()
        return extension in listOf("jpg", "jpeg", "png", "bmp", "gif", "webp")
    }
    
    /**
     * 判断是否为文本文件
     */
    private fun isTextFile(path: String): Boolean {
        val extension = File(path).extension.lowercase()
        return extension in listOf("txt", "md", "json", "xml")
    }
}